package com.atguigu.tingshu.order.strategy.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.google.common.collect.Lists;


import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.order.strategy.OrderTradeStrategy;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
//专辑购买实现类
public class AlbumOrderTradeStrategy implements OrderTradeStrategy {

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public OrderInfoVo trade(TradeVo tradeVo) {

        Long albumId = tradeVo.getItemId();
        //判断用户是否购买过当前专辑
        Result<Boolean> booleanResult = userInfoFeignClient.isPaidAlbum(albumId);
        Boolean aBoolean = booleanResult.getData();
        //购买过该专辑
        if (aBoolean) {
            throw new GuiguException(ResultCodeEnum.REPEAT_BUY_ERROR);
        }

        // 构建OrderInfoVo对象
        OrderInfoVo orderInfoVo = new OrderInfoVo();

        // 根据专辑的id查询专辑数据
        Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfo(albumId);
        AlbumInfo albumInfo = albumInfoResult.getData();


        //获取当前用户信息
        Long userId = AuthContextHolder.getUserId();
        Result<UserInfoVo> userInfoVoByUserIdResult = userInfoFeignClient.findUserInfoVoByUserId(userId);
        UserInfoVo userInfoVo = userInfoVoByUserIdResult.getData();

        // 金额数据的构建
        BigDecimal originalAmount = albumInfo.getPrice();
        orderInfoVo.setOriginalAmount(originalAmount);


        //判断用户是否为vip用户,并且判断vip是否过期
        if (userInfoVo.getIsVip().equals("1") && new Date().before(userInfoVo.getVipExpireTime())) {
            // 按照vip的折扣进行减免金额
            BigDecimal vipDiscount = albumInfo.getVipDiscount();
            if (vipDiscount.intValue() != -1) {
                BigDecimal orderAmount = originalAmount.multiply(vipDiscount)
                        .multiply(new BigDecimal("10"))
                        .divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
                orderInfoVo.setDerateAmount(albumInfo.getPrice().subtract(orderAmount));
                orderInfoVo.setOrderAmount(orderAmount);
            } else {
                orderInfoVo.setDerateAmount(new BigDecimal("0.00"));
                orderInfoVo.setOrderAmount(originalAmount);
            }
        } else {
            // 按照普通的用户的折扣进行减免金额
            BigDecimal discount = albumInfo.getDiscount();
            if (discount.intValue() != -1) {
                BigDecimal orderAmount = originalAmount.multiply(discount)
                        .multiply(new BigDecimal("10"))
                        .divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
                orderInfoVo.setDerateAmount(albumInfo.getPrice().subtract(orderAmount));
                orderInfoVo.setOrderAmount(orderAmount);
            } else {// 不需要进行打折
                orderInfoVo.setDerateAmount(new BigDecimal("0.00"));
                orderInfoVo.setOrderAmount(originalAmount);
            }
            orderInfoVo.setDerateAmount(originalAmount.subtract(orderInfoVo.getOrderAmount()));
        }


        // 订单明细数据
        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setItemId(albumId);
        orderDetailVo.setItemName(albumInfo.getAlbumTitle());
        orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
        orderDetailVo.setItemPrice(albumInfo.getPrice());
        orderInfoVo.setOrderDetailVoList(Arrays.asList(orderDetailVo));


        //订单减免明细列表
        if (0 != orderInfoVo.getDerateAmount().intValue()) {
            OrderDerateVo orderDerateVo = new OrderDerateVo();
            orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);
            orderDerateVo.setDerateAmount(orderInfoVo.getDerateAmount());
            orderDerateVo.setRemarks("专辑购买折扣");
            orderInfoVo.setOrderDerateVoList(Arrays.asList(orderDerateVo));
        }


        //设置其他的数据

        orderInfoVo.setTimestamp(SignHelper.getTimestamp());//当前系统时间
        Map<String, Object> map = JSON.parseObject(JSON.toJSONString(orderInfoVo), Map.class);
        String sign = SignHelper.getSign(map);
        orderInfoVo.setSign(sign);
        orderInfoVo.setItemType(tradeVo.getItemType());
        //创建一个UUID作为交易编号
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        orderInfoVo.setTradeNo(tradeNo);
        orderInfoVo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);

        String tradeNoRedisKey = RedisConstant.ORDER_TRADE_NO + tradeNo;
        redisTemplate.opsForValue().set(tradeNoRedisKey, tradeNo, 5, TimeUnit.MINUTES);


        return orderInfoVo;
    }

    @Override
    public String getItemType() {
        return SystemConstant.ORDER_ITEM_TYPE_ALBUM;
    }
}
